package com.neusoft.neuiotms.dcam.fixed.repository.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import com.neusoft.bizcore.web.jpa.repository.AbstractRepository;
import com.neusoft.bizcore.web.support.Searchable;
import com.neusoft.neuiotms.dcam.fixed.model.Product;
import com.neusoft.neuiotms.dcam.fixed.model.QProduct;
import com.neusoft.neuiotms.dcam.fixed.repository.CustomizedProductRepository;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQuery;

public class CustomizedProductRepositoryImpl extends AbstractRepository
        implements CustomizedProductRepository {

    @Override
    public List<Product> index(final Searchable searchable) {
        final QProduct qProduct = QProduct.product;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<Product> query = this.query().selectFrom(qProduct);
        query.where(where);
        return query.fetch();
    }

    @Override
    public Page<Product> search(final Pageable pageable, final Searchable searchable) {
        final QProduct qProduct = QProduct.product;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<Product> query = this.query().selectFrom(qProduct);
        query.where(where);
        return super.search(query, pageable);
    }

    @Override
    protected Class<?> getModelClass() {
        return Product.class;
    }

    private BooleanBuilder buildWhere(final Searchable searchable) {
        final BooleanBuilder where = new BooleanBuilder();
        final QProduct qProduct = QProduct.product;
        where.and(super.containsStr(qProduct.name, searchable, "name"));
        if (!StringUtils.isEmpty(searchable.getStrValue("assetTypeCode"))) {
            where.and(super.equalsStr(qProduct.assetType.code, searchable, "assetTypeCode"));//类型code
        }
        where.and(super.equalsStr(qProduct.belongs, searchable, "belongs"));
        return where;
    }

}
